package lihua.robot.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lihua.robot.controller.BlocksController;
import lihua.robot.utils.RedisUtil;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class MqttUtil {

    private static final String MQTT_URL = "tcp://172.16.1.100:1883";
    private static final String MQTT_CLIENT_ID = "461adc7343d94cc5b0a506fd5b1fc11f";
    private static final int MQTT_QOS = 2;
    private static final String MQTT_USERNAME = "";
    private static final String MQTT_PASSWORD = "";
    private static final int MQTT_KEEP_ALIVE_INTERVAL = 60 * 3;

    // 三纺
    private static final List<String> topicList3 = Arrays.asList(
            "WG581WLAN22101302145",
            "WG581WLAN22101302154",
            "WG581WLAN22101302155",
            "WG581WLAN22101302141",
            "WG581WLAN22101302118",
            "WG581WLAN22101302119",
            "WG581WLAN22101701119",
            "WG581WLAN22101302138"
    );
//    private static final List<String> topicList3 = Arrays.asList(
//            "WG581WLAN22101302154"
//    );
    public static void getMqttMessage() {
        MqttClient mqttClient = null;

        try {
            mqttClient = new MqttClient(MQTT_URL, MQTT_CLIENT_ID);
            MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
            mqttConnectOptions.setUserName(MQTT_USERNAME);
            mqttConnectOptions.setPassword(MQTT_PASSWORD.toCharArray());
            mqttConnectOptions.setKeepAliveInterval(MQTT_KEEP_ALIVE_INTERVAL);
            mqttClient.connect(mqttConnectOptions);

            for (String topic : topicList3) {
                mqttClient.subscribe("/sys/" + topic + "/up", MQTT_QOS);
            }

            // Set callback functions
            mqttClient.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                }

                @Override
                public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
                    String jsonPayload = new String(mqttMessage.getPayload());

                    //解析json
                    JSONObject jsonObject = JSONUtil.parseObj(jsonPayload);
                    String now_devlist = jsonObject.getStr("devList");
                    String now_devList = now_devlist.replace("[", "").replace("]", "");

                    JSONObject devList = JSONUtil.parseObj(now_devList);
                    String now_varList = devList.getStr("varList");
                    JSONObject varList =  JSONUtil.parseObj(now_varList);

                    Integer dqcd = varList.getInt("dqcd");//当前长度
                    Integer devSn = devList.getInt("devSn");//设备号
                    Integer cmdId = jsonObject.getInt("cmdId");



                    //存入redis
                    if(cmdId == 103 && dqcd != null) {
                        System.out.println(DateUtil.date() +"----设备"+devSn+":"+dqcd);
                        RedisUtil.storeDataInCache(devSn,dqcd);
                    }

                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                    // Not used in this example
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void runMQTT() {
        System.out.println("运行mqtt");
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5); // 创建一个拥有5个线程的线程池
        Runnable task = () -> {
            getMqttMessage();
        };
        // 延迟0秒后开始执行任务，每隔1秒执行一次
        executorService.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
    }

}
